package com.soulkun.smarthome.ui.main.personal.viewmodel

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.soulkun.smarthome.logic.model.ResponseModel
import com.soulkun.smarthome.logic.model.RoomModel
import com.soulkun.smarthome.logic.repository.ApiRepository
import com.soulkun.smarthome.logic.vo.RoomVO

class AppMainPersonalFamilySettingRoomViewModel : ViewModel() {

    var familyId: Long? = null
    val selectFamilyRoomLiveData = MutableLiveData<RoomVO>()
    val managerStatus = ObservableBoolean(false)
    val familyRoomList = ObservableArrayList<RoomVO>()

    fun addRoom(roomName: String, onComplete: (ResponseModel<RoomModel>) -> Unit) {
        ApiRepository.addRoom(
            this,
            RoomModel(
                name = roomName,
                familyId = familyId
            )
        ) {
            familyRoomList.add(
                RoomVO(it.data.id!!, ObservableField(it.data.name), it.data.familyId!!)
            )
            onComplete(it)
        }
    }

    fun deleteRoom(onComplete: (ResponseModel<Any>) -> Unit) {
        ApiRepository.deleteRoom(
            this,
            RoomModel(
                selectFamilyRoomLiveData.value!!.id,
                familyId = familyId
            )
        ) {
            familyRoomList.remove(selectFamilyRoomLiveData.value!!)
            onComplete(it)
        }
    }

    fun modifyRoomName(roomName: String, onComplete: (ResponseModel<Any>) -> Unit) {
        ApiRepository.modifyRoomName(
            this,
            RoomModel(
                name = roomName,
                id = selectFamilyRoomLiveData.value!!.id,
                familyId = familyId
            )
        ) {
            familyRoomList.find { familyRoom -> familyRoom.id == selectFamilyRoomLiveData.value!!.id }?.name?.set(
                roomName
            )
            onComplete(it)
        }
    }

}